﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using myMvcBlog.Models;
using System.Configuration;
using System.Web.Security;
using myMvcBlog.Infrastructure;

namespace myMvcBlog.Controllers
{
    public class AdminController : BaseController
    {
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            AdminHomeView homeView = new AdminHomeView();

            homeView.PostCount = Post.All().Count();
            homeView.CategoryCount = Category.All().Count();
            homeView.CommentCount = Comment.All().Count();
            homeView.TagCount = myMvcBlog.Tag.All().Count();

            return View(homeView);
        }

        public ActionResult Posts(int? page)
        {
            var post = Post.All().OrderByDescending(p => p.PostedTime);

            ListView<Post> postListView = new ListView<Post>();
            postListView.List = post.Skip((page ?? 0) * ItemsPerPage * 2).Take(ItemsPerPage * 2).ToList();

            PagerView pager = new PagerView();
            pager.PageCount = (int)Math.Ceiling((double)post.Count() / (ItemsPerPage * 2));
            pager.CurrentPage = page ?? 0;
            pager.ActionName = "Posts";
            pager.ControllerName = "Admin";

            postListView.Pager = pager;
            return View(postListView);
        }

        public ActionResult PostsByCategory(long categoryId, int? page)
        {
            ListView<Post> lvPosts = new ListView<Post>();
            lvPosts.Title = "Posts under :" + Category.SingleOrDefault(c => c.ID == categoryId).Name;
            var postIds = from pc in PostCategory.All()
                          where pc.CategoryID == categoryId
                          select pc.PostID;

            var posts = (from p in Post.All()
                         join pid in postIds on p.ID equals pid
                         select p).OrderByDescending(p => p.PostedTime);

            lvPosts.List = posts.Skip((page ?? 0) * ItemsPerPage * 2).Take(ItemsPerPage * 2).ToList();
            PagerView pager = new PagerView();
            pager.PageCount = (int)Math.Ceiling((double)posts.Count() / (ItemsPerPage * 2));
            pager.CurrentPage = page ?? 0;
            pager.ActionName = "PostsByCategory";
            pager.ControllerName = "Admin";

            lvPosts.Pager = pager;
            return View(lvPosts);
        }

        public ActionResult DeletePost(long postId)
        {
            var post = Post.SingleOrDefault(p => p.ID == postId);
            post.Delete();

            return RedirectToAction("Posts");
        }

        [HttpGet]
        public ActionResult AddPost()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddPost(Post post, string category)
        {
            post.Save();

            PostCategory pt = new PostCategory();
            pt.PostID = post.ID;
            pt.CategoryID = long.Parse(category);
            pt.Save();

            return RedirectToAction("Posts");
        }

        public ActionResult Categories()
        {
            var categories = Category.All().ToList();
            return View(categories);
        }

        public ActionResult EditCategory(long id)
        {
            Category cat = Category.SingleOrDefault(category => category.ID == id);
            return View(cat);
        }

        public ActionResult Comments(int? page)
        {
            var cmts = Comment.All().OrderByDescending(c => c.CommentTime);

            ListView<Comment> lvComments = new ListView<Comment>();
            lvComments.List = cmts.Skip((page ?? 0) * ItemsPerPage).Take(ItemsPerPage).ToList();

            PagerView pager = new PagerView();
            pager.PageCount = (int)Math.Ceiling((double)cmts.Count() / ItemsPerPage);
            pager.CurrentPage = page ?? 0;
            pager.ActionName = "Comments";
            pager.ControllerName = "Admin";

            lvComments.Pager = pager;

            return View(lvComments);
        }

        public ActionResult DeleteComment(long id)
        {
            var comment = Comment.SingleOrDefault(c => c.ID == id);
            comment.Delete();

            return RedirectToAction("Comments");
        }

        public ActionResult Tags(int? page)
        {
            var tags = myMvcBlog.Tag.All().OrderByDescending(t => t.AddedTime);

            ListView<Tag> lvTags = new ListView<Tag>();
            lvTags.List = tags.Skip((page ?? 0) * ItemsPerPage * 2).Take(ItemsPerPage * 2).ToList();

            PagerView pager = new PagerView();
            pager.PageCount = (int)Math.Ceiling((double)tags.Count() / (ItemsPerPage * 2));
            pager.CurrentPage = page ?? 0;
            pager.ActionName = "Tags";
            pager.ControllerName = "Admin";

            lvTags.Pager = pager;

            return View(lvTags);
        }

        [HttpGet]
        public ActionResult Tag(long id)
        {
            myMvcBlog.Tag tag = myMvcBlog.Tag.SingleOrDefault(t => t.ID == id);

            return View(tag);
        }

        [HttpPost]
        public ActionResult Tag(long id, string name, string encodedName, bool isActive)
        {
            myMvcBlog.Tag tag = myMvcBlog.Tag.SingleOrDefault(t => t.ID == id);
            if (tag != null && tag.ID > 0)
            {
                tag.Name = name;
                tag.AddedTime = DateTime.Now;
                tag.IsActive = isActive;

                tag.Save();

                return RedirectToAction("Tags");
            }
            else
            {
                throw new KeyNotFoundException("tag with id equals: " + id.ToString() + " doesn't exists");
            }
        }

        public ActionResult DeleteTag(long id)
        {
            var tag = myMvcBlog.Tag.SingleOrDefault(t => t.ID == id);
            tag.Delete();

            return RedirectToAction("Tags");
        }

        [HttpGet]
        public ActionResult Edit(long postId)
        {
            Post post = Post.All().SingleOrDefault(p => p.ID == postId);
            return View(post);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Post post, string category)
        {
            Post p = Post.SingleOrDefault(po => po.ID == post.ID);
            if (p != null)
            {
                p.Name = post.Name;
                p.UrlName = post.UrlName;
                p.Excerpt = post.Excerpt;
                p.Content = post.Content;
                p.IsPublished = post.IsPublished;
                p.Save();

                PostCategory.GetRepo().Delete(PostCategory.All().Where(pt => pt.PostID == post.ID));

                PostCategory postCategory = new PostCategory()
                {
                    PostID = post.ID,
                    CategoryID = long.Parse(category)
                };

                postCategory.Save();
            }

            return RedirectToAction("Edit");
        }

        [HttpGet]
        public ActionResult Logon()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Logon(string name, string password)
        {
            if (name == "jun1st" && password == ConfigurationManager.AppSettings["Password"])
            {
                FormsAuthentication.SetAuthCookie("jun1st", false);
                return RedirectToAction("Index");
            }
            else
            {
                return RedirectToAction("Logon");
            }
        }

    }
}
